import json
from prance import ResolvingParser
from jsonpath_ng import parse

def build_tree(schema, path="", parent=None):
    node = {
        "name": schema.get("description", ""),
        "jsonpath": path,
        "type": schema.get("type", ""),
        "comment": schema.get("description", ""),
        "ref": schema.get("$ref", ""),
        "children": []
    }
    if "properties" in schema:
        for prop, prop_schema in schema["properties"].items():
            child_path = f"{path}.{prop}" if path else prop
            child_node = build_tree(prop_schema, child_path, node)
            node["children"].append(child_node)
    elif "items" in schema:
        child_node = build_tree(schema["items"], f"{path}[*]", node)
        node["children"].append(child_node)
    return node

def parse_openapi_spec(file_path):
    parser = ResolvingParser(file_path)
    spec = parser.specification

    interfaces = []

    for path, path_item in spec["paths"].items():
        for method, operation in path_item.items():
            interface = {
                "method": method,
                "url": path,
                "url_params": [param for param in operation.get("parameters", []) if param["in"] == "path"],
                "query_params": [param for param in operation.get("parameters", []) if param["in"] == "query"],
                "name": operation.get("summary", ""),
                "request_body": None,
                "response_body": None
            }

            if "requestBody" in operation:
                request_schema = operation["requestBody"]["content"]["application/json"]["schema"]
                interface["request_body"] = build_tree(request_schema)

            for response_code, response in operation.get("responses", {}).items():
                if "content" in response and "application/json" in response["content"]:
                    response_schema = response["content"]["application/json"]["schema"]
                    interface["response_body"] = build_tree(response_schema)

            interfaces.append(interface)

    return interfaces

if __name__ == "__main__":
    interfaces = parse_openapi_spec("openapi.yaml")
    with open("static/data/interfaces_define.json", "w", encoding="utf-8") as f:
        json.dump(interfaces, f, ensure_ascii=False, indent=4)
    print(json.dumps(interfaces, indent=4, ensure_ascii=False))
